<?php

namespace Beerus\Modules\NewProduct\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\brandRights\BrandRightsRecored;
use Biz\model\NewProduct\NewProductJdCardModel;
use Biz\model\NewProduct\NewProductJoinRecordModel;
use Biz\model\NewProduct\NewProductTagModel;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\wiki\Wiki;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Biz\service\NewProduct\NewProductService;
use Biz\tools\FormatDate;
use Biz\tools\helper\Common;
use Doraemon\model\ImageCreate\ImageCreate as mImageCreate;
use Doraemon\tools\ImageCreate;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;

/**
 * Description: wwwroot
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/24
 * Time: 18:17
 */
class IndexController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->auditScript());
        Admin::script($this->sendJdCardScript());
        Admin::script($this->createImgScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $list = NewProductWikiModel::all($where, '*');

        unset($where['LIMIT']);
        $count = NewProductWikiModel::count($where);

        $list = NewProductService::formatList($list);

        foreach ($list as &$item) {
            $item['data_list'] = $item['id'] ? $this->_getExpand($item['id']) : '';
        }

        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                //显示当前页的序号
                $grid->number('序号');
                $grid->rows(function ($row, $number) {
                    $row->column('number', $number + 1);
                });

                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('wiki_id', '商品ID')->placeholder('商品ID');
                        $filter->equal('basic_id', 'WIKI_ID')->placeholder('WIKI_ID');
                        $filter->equal('type', '活动类型')->select([
                            '1' => '超级新品',
                            '2' => '甄选新品',
                        ]);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_name', '品牌名称')->placeholder('品牌名称');
                        $filter->equal('start_time', '上线时间')->date();
                        $filter->equal('status', '活动状态')->select(NewProductWikiModel::ACT_STATUS);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
//                $grid->column('id', 'id')->sortable();
                $grid->column('id', '活动ID')->modal(function () {
                    return $this->data_list;
                });
                $grid->column('brand_name', '品牌名称');
                $grid->column('basic_id', 'WIKI_ID');
                $grid->column('wiki_id', '商品ID');
//                $grid->column('img_url', '商品图片')->image();
                $grid->column('img_url', '商品图片')->display(function ($img_url) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'500px\'],content: \'' . $img_url . '\'});">
                                <img width="100px" height="100px" src="' . $img_url . '">
                            </a>';
                });

                $grid->column('name', '名称')->width(200);
                $grid->column('type', '活动类型')->using([
                    1 => '超级新品',
                    2 => '甄选新品',
                ]);

                $grid->column('start_time', '上线时间')->display(function ($start_time) {
                    $start_time = $start_time == FormatDate::DEFAULT_DATE_TIME ? FormatDate::DEFAULT_DATE : date("Y-m-d", strtotime($start_time));
                    $end_time = $this->end_time == FormatDate::DEFAULT_DATE_TIME ? FormatDate::DEFAULT_DATE : date("Y-m-d", strtotime($this->end_time));
                    return "$start_time ~ $end_time";
                })->sortable();
                $grid->column('dynamic_img')->display(function ($dynamic_img) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'751px\', \'500px\'],content: \'' . $dynamic_img . '\'});">
                                <img width="200px" height="100px" src="' . $dynamic_img . '">
                            </a>';
                });
                $grid->column('dynamic_status', '动态图片')->using(NewProductWikiModel::DYNAMIC_STATUS)->label([
                    1 => 'success',
                    2 => 'danger',
                ]);
                $grid->column('is_delete', '删除状态')->using(
                    [
                        NewProductWikiModel::DELETED => '已删除',
                        NewProductWikiModel::NO_DELETED => '正常',
                    ]
                )->label([
                    2 => 'success',
                    1 => 'danger',
                ]);
                $grid->column('status', '状态')->using(
                    NewProductWikiModel::ACT_STATUS
                    , '未知')->label([
                    1 => 'success',
                    5 => 'warning',
                    2 => 'danger',
                    3 => 'info',
                    4 => 'primary',
                ]);
                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $html_pass = ' <a class="fa edit-pass-data" data-state="' . NewProductWikiModel::STATUS_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-ok" aria-hidden="true">通过</span></a>';
                    $html_unpass = '<a class="fa edit-pass-data" data-state="' . NewProductWikiModel::STATUS_REJECT . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-remove" aria-hidden="true">不通过</span></a>';
                    switch ($actions->row->status) {
                        case NewProductWikiModel::STATUS_REJECT:
                        case NewProductWikiModel::STATUS_END:
                        case NewProductWikiModel::STATUS_ACTING:
                        case NewProductWikiModel::STATUS_PASS:
                            break;
                        case NewProductWikiModel::STATUS_WAIT:
                            $actions->prepend($html_pass);
                            $actions->prepend($html_unpass);
                            break;
                    }
                    if ($actions->row->type == NewProductWikiModel::SUPER_PDT) {
                        $actions->prepend(
                            ' <a class="fa edit-create"  data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon glyphicon-sound-dolby" aria-hidden="true">生成图片</span></a>');
                    }
                    //超级新品-京东兑换码「活动结束」状态，展示「奖品详情」入口，但无「操作」那一列
                    if ($actions->row->type == NewProductWikiModel::SUPER_PDT && $actions->row->status == NewProductWikiModel::STATUS_END) {
                        $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/newProduct/winnerList?nid=' . $actions->row->id) . '">
                                                <span class="glyphicon glyphicon-eye-open" aria-hidden="true">中奖信息</span></a>');
                    }
                    //甄选新品「活动中」状态，展示「京东卡发放」
                    if ($actions->row->type == NewProductWikiModel::GRACE_PDT && $actions->row->status == NewProductWikiModel::STATUS_ACTING) {
                        $actions->prepend('<a class="fa fa-edit send-jd-card" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>京东卡发放</a>');
                    }
                    //甄选新品-邮寄方式「活动结束」状态，展示「奖品详情」 如果是京东卡方式 则不展示奖品详情
                    if ($actions->row->type == NewProductWikiModel::GRACE_PDT && $actions->row->status == NewProductWikiModel::STATUS_END) {
                        $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/newProduct/winnerList?nid=' . $actions->row->id) . '">
                            <span class="glyphicon glyphicon-eye-open" aria-hidden="true">中奖信息</span></a>');
                    }
                    if ($actions->row->status == NewProductWikiModel::STATUS_END) {
                        $btnTitle = $actions->row->activity_data ? '编辑数据' : '上传数据';
                        $actions->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="fa fa-bar-chart" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑数据\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'700px\'],
                                content: \'/admin/newProduct/index/' . $actions->row->id . '/activityData\'
                            });" title="' . $btnTitle . '"><i class="fa"></i><span class="hidden-xs">' . $btnTitle . '</span></a>
</div>');
                    }
                });
            }
        );
        $tab = new Tab();
        $tab->add('新品速递审核', $grid->render(), true);
        $tab->addLink('上线排序', url('/admin/newProduct/sortlists'), false);
        $content->row($tab);

        return $content
            ->header('新品速递活动')
            ->description(' ')
            ->breadcrumb(['text' => '新品速递审核', 'url' => '/newProduct/index']);
    }


    /**
     * 子页面
     * @param $nid
     * @return string
     */
    private function _getExpand($nid): string
    {
        $row = new Row();
        //参与总数
        $count = NewProductJoinRecordModel::count(['nid' => $nid]);
        //标签列表
        $tag_list = NewProductTagModel::all(['nid' => $nid], ['id', 'tag']);

        $sql = 'SELECT count(id) as num, tid  FROM new_product_join_record WHERE nid =' . $nid . ' GROUP BY tid';
        $record = NewProductJoinRecordModel::query($sql)->fetchAll();
        $record_list = array_column($record, 'num', 'tid');
        $list = [];
        foreach ($tag_list as $k => $item) {
            $list[$k]['tag'] = $item['tag'];
            $list[$k]['total'] = $record_list[$item['id']] ?: 0;
            $list[$k]['percentage'] = $count != 0 ? round($record_list[$item['id']] / $count * 100) . '%' : 0;
        }

        $gridModel = new GridDataModel($list, null, ['pageName' => '']);
        $grid = new Grid($gridModel);
        $grid->disablePagination();
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableRowSelector();
        $grid->disableColumnSelector();
        $grid->disableTools();
        $grid->disableExport();
        $grid->disableActions();

        $grid->column('tag', '选项名称');
        $grid->column('total', '选择数量');
        $grid->column('percentage', '该选项占比');
        $row->column(12, $grid);

        return $row->render();
    }

    private function auditScript()
    {
        return <<<SCRIPT
        $('.edit-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/newProduct/audit'
            let params = {id:id,state:state}
            swal({
                    title: "确认提交吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }

    private function sendJdCardScript(): string
    {
        return <<<SCRIPT
        $('.send-jd-card').unbind('click').click(function(){
            var id=$(this).data('id');
            layer.open({
                type: 2,
                title: '填写京东兑换码',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['600px', '600px'],
                content: '/admin/newProduct/jdCard/'+id+'/add',
            });
        });
SCRIPT;
    }

    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $id = $params['id'] ?? 0;
        $wiki_id = $params['wiki_id'] ?? 0;
        $basic_id = $params['basic_id'] ?? 0;
        $type = $params['type'] ?? 0;
        $page = $params['page'] ?? 1;
        $page_size = $params['per_page'] ?? 20;
        $brand_name = $params['brand_name'] ?? '';
        $start_time = $params['start_time'] ? date('Y-m-d H:i:s', strtotime($params['start_time'])) : 0;
        $status = $params['status'] ?? "";
        if ($id) {
            $where['id'] = $id;
        }
        if ($wiki_id) {
            $where['wiki_id'] = $wiki_id;
        }
        if ($basic_id) {
            $where['basic_id'] = $basic_id;
        }
        if ($type) {
            $where['type'] = $type;
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
        }
        if ($brand_name) {
            $where['brand_name[~]'] = $brand_name . '%';
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
        }
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        if ($status) {
            //活动中
            if ((int)$status === NewProductWikiModel::STATUS_ACTING) {
                $status = NewProductWikiModel::STATUS_PASS;
                $where['start_time[<=]'] = date('Y-m-d H:i:s');
                $where['end_time[>]'] = date('Y-m-d H:i:s');

            }
            //活动结束
            if ((int)$status === NewProductWikiModel::STATUS_END) {
                $where['end_time[<]'] = date('Y-m-d H:i:s');
                $status = NewProductWikiModel::STATUS_PASS;
            }
            $where['status'] = $status;

        } else {
            $where['status[>]'] = 0;
        }
        if (isset($params['_sort']["column"], $params['_sort']["type"])) {
            $where['ORDER'] = [
                $params['_sort']["column"] => strtoupper($params['_sort']["type"]),
            ];
        } else {
            $where['ORDER'] = [
                'sort' => "DESC",
                'start_time' => 'DESC',
            ];
        }

        return $where;
    }

    /**
     * 排序
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function sortLists(Request $request, Content $content): Content
    {
        $params = $request->all();
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $count = NewProductWikiModel::count($where);
        $where['start_time[<=]'] = date('Y-m-d H:i:s');
        $where['end_time[>]'] = date('Y-m-d H:i:s');
        $where['type'] = NewProductWikiModel::SUPER_PDT;
        if ($params['type']) {
            $where['type'] = $params['type'];
        }
        $where['ORDER'] = [
            'sort' => "DESC",
            'start_time' => 'DESC',
        ];

        $list = NewProductWikiModel::all($where, '*');
        $list = NewProductService::formatList($list);
        $gridModel = new GridDataModel($list, $count);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disablePagination();
                $grid->disableCreateButton();
//                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('type', '活动类型')->select([
                            NewProductWikiModel::SUPER_PDT => '超级新品',
                            NewProductWikiModel::GRACE_PDT => '甄选新品',
                        ])->default(NewProductWikiModel::SUPER_PDT);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id')->sort()->sortable();
                $grid->column('brand_name', '品牌名称');
                $grid->column('wiki_id', '商品ID');
                $grid->column('img_url', '商品图片')->image();
                $grid->column('name', '名称');

                $grid->column('type', '活动类型')->using([
                    1 => '超级新品',
                    2 => '甄选新品',
                ]);

                $grid->column('start_time', '上线时间')->sortable();
//                        $grid->column('end_time', '结束时间')->sortable();
//                        $grid->column('create_time', '创建时间')->sortable();

                $grid->column('status', '状态')->using(
                    NewProductWikiModel::ACT_STATUS
                    , '未知')->label([
                    1 => 'success',
                    5 => 'warning',
                    2 => 'danger',
                    3 => 'info',
                    4 => 'primary',
                ]);
                $grid->disableActions();
            }
        );
        $tab = new Tab();
        $tab->addLink('新品速递审核', url('/admin/newProduct/index'), false);
        $tab->add('上线排序', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('上线排序')
            ->description(' ')
            ->breadcrumb(['text' => '上线排序', 'url' => '/newProduct/sortlists']);


    }

    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content|Application|RedirectResponse|Redirector
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        $where['id'] = $id;
        //编辑wiki
        $baseInfo = NewProductWikiModel::first($where);

        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);

            return back()->with(compact('error'));
        }
        $tags = NewProductService::getTagsByNid([$baseInfo['id']]);
        $baseInfo['tag'] = $tags;
        $baseInfo['price'] = $baseInfo['price'] ? bcdiv($baseInfo['price'], 100, 2) : 0.00;
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        // 显示记录id
        $baseForm->text('id', 'ID')->disable();
        $baseForm->hidden('id');
        $baseForm->hidden('brand_id');
        $baseForm->text('brand_id', '品牌ID')->disable();
        $this->_getForm($baseForm);
        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/newProduct/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动列表', 'url' => '/newProduct/index'],
                ['text' => '活动修改']
            )
            ->row($baseForm);

    }

    /**
     * form
     * @param $baseForm
     */
    private function _getForm($baseForm)
    {
        $baseForm->text('brand_name', '品牌名称')->required();
        $baseForm->text('name', '商品名称')->required();
        $baseForm->imgUpload('img', '商品主图', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->help("仅支持一张图片上传");
        $baseForm->text('basic_id', 'wiki_id')->required();
        $baseForm->textarea('desc', '简介')->required();
        $options = [
            '1' => '超级新品',
            '2' => '甄选新品',
        ];
        $baseForm->select('type', '活动类型')->options($options)->when(1, function (Form $baseForm) {
            $baseForm->text('prize_name', '奖品名称');
            $baseForm->text('prize_num', '奖品个数')->default(0);
            $baseForm->text('price', '奖品单价')->default(0.00);
            $baseForm->text('question', '问题');
        });
//        $baseForm->text('question', '问题');
        $baseForm->table('tag', '选项/原因', function ($table) {
            $table->text('tag')->required();
            $table->hidden('id');
        })->required()->help('必传');
        $baseForm->text('features', '新品特点')->required()->help('多个用","隔开');
        $baseForm->date('start_time', '开始时间')->required();
        $baseForm->date('end_time', '结束时间')->required();
    }

    /**
     * 保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        $params = $request->all();
        $type = $params["type"];
        $rules = $this->_getRules($type);
        //校验参数
        $res_msg = Common::validatorRule($rules, $params);
        if ($res_msg !== true) {
            $error = new MessageBag([
                'title' => $res_msg,
            ]);
            return back()->with(compact('error'));
        }
        $data = [
            "type" => $params["type"],
            "brand_id" => $params["brand_id"],
            "brand_name" => $params["brand_name"],
            "img" => $params["img"] ?? '',
            "basic_id" => $params["basic_id"] ?? 0,
            'url' => $params['url'] ?? '',
            'jump_type' => $params['jump_type'] ?? 1,
            "name" => $params["name"],
            "desc" => $params["desc"],
            "features" => $params["features"] ? str_replace('，', ',', $params['features']) : '',
            "question" => $params["question"] ?? '',
            "start_time" => date('Y-m-d H:i:00', strtotime($params["start_time"])),
            "month" => date('Y-m', strtotime($params["start_time"])),
            "end_time" => date('Y-m-d H:i:s', strtotime($params["end_time"]) + 86399),
            "prize_name" => $params["prize_name"] ?? '',
            "prize_num" => $params["prize_num"] ?? 0,
            "price" => $params["price"] ? bcmul($params["price"], 100) : 0,
            "update_time" => date('Y-m-d H:i:s'),
        ];
        $data['dynamic_status'] = NewProductWikiModel::UNCREATED;
        if ($type == NewProductWikiModel::GRACE_PDT) {
            $data['dynamic_status'] = NewProductWikiModel::CREATED;
            $data['dynamic_img'] = NewProductWikiModel::IMG_ID_GRACE_PDT;
        }
        $wiki_id = Wiki::getDefaultWikiByBasicId($data['basic_id'], $params["brand_id"], 'id');
        if (!$wiki_id) {
            $error = new MessageBag([
                'title' => '商品不存在',
            ]);

            return back()->with(compact('error'));
        }
        $data['wiki_id'] = $wiki_id;
        $tag_data = $params['tag'];
        sort($tag_data);
        $tags = Common::arrayFilterFieldValue($tag_data, '_remove_', 0) ?: [];
        if (!$tags) {
            $error = new MessageBag([
                'title' => '选项/原因必传',
            ]);

            return back()->with(compact('error'));
        }
        if (count($tags) !== 4) {
            $error = new MessageBag([
                'title' => '选项/原因请填写4项',
            ]);

            return back()->with(compact('error'));
        }
        //更新
        if (isset($params['id']) && $params['id']) {
            $this->updateData($tag_data, $params, $data);
        } else {
            $nid = $this->insertData($tag_data, $params, $data);
            if ($nid) {
                //权益数量操作
                $sourceId = BrandActivityBasic::getSourceId(BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT, $nid);
                $dataParams = [
                    $params["brand_id"],
                    SourceRightsInterface::NEW_PRODUCT,
                    BrandRightsRecored::RECORED_TYPE_CONSUME,
                    BrandRightsRecored::OPERATE_USER_TYPE_SYS,
                    $sourceId,
                ];

                $res = BrandEquityVerificationService::addOrSubBrandSourceNum(...$dataParams);
                if (!$res) {
                    throw new \Exception('系统错误！请重试');
                }
            }
        }
        $success = new MessageBag([
            'title' => '成功',
        ]);
        //更新
        if (isset($params['id']) && $params['id']) {
            return redirect('/admin/newProduct/index/' . $params['id'] . '/edit')->with(compact('success'));
        }

        return redirect('/admin/newProduct/index')->with(compact('success'));
    }

    /**
     * 更新
     * @param $tag_data
     * @param $params
     * @param $data
     * @return bool
     */
    private function updateData($tag_data, $params, $data)
    {
        $tag_del_ids = [];
        foreach ($tag_data as $tag) {
            if ($tag['_remove_'] != 1) {
                if (!$tag['id']) {
                    $in_data['tag'] = $tag['tag'];
                    $in_data['nid'] = $params['id'];
                    $in_data['type'] = $params['type'];
                    $in_data['status'] = NewProductTagModel::STATUS_ON;
                    NewProductTagModel::insert($in_data);
                } else {
                    $tag_up_data['tag'] = $tag['tag'];
                    $up_where['id'] = $tag['id'];
                    NewProductTagModel::update($tag_up_data, $up_where);
                }
            } else {
                $tag_del_ids[] = $tag['id'];
            }
        }
        if ($tag_del_ids) {
            NewProductTagModel::update([
                'status' => NewProductTagModel::STATUS_OFF,
                'update_time' => date('Y-m-d H:i:s'),
            ], ['id' => $tag_del_ids]);
        }
        $where['id'] = $params['id'];
        NewProductWikiModel::update($data, $where);
        $params['activity_id'] = $params['id'];
        $this->saveActBasic($params);
        return true;
    }

    /**
     * 保存活动主表
     * @param $params
     * @return bool
     */
    private function saveActBasic($params)
    {
//        if ((int)$params['status'] == NewProductWikiModel::STATUS_PASS) {
//            $status = BrandActivityBasic::ACTIVITY_STATE_NORMAL;
//        } else {
//            $status = BrandActivityBasic::ACTIVITY_STATE_DEL;
//        }
        $pa_data['activity_id'] = $params['activity_id'];
        $pa_data['activity_type'] = BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT;
        $pa_data['brand_id'] = $params['brand_id'];
        $pa_data['end_time'] = $params['end_time'];
        $pa_data['start_time'] = $params['start_time'];
        $pa_data['basic_id'] = $params['basic_id'];
        //$pa_data['activity_state'] = $status;
        BrandActivityBasic::saveNewProActivity($pa_data);
        return true;
    }

    /**
     * 新增 （不在提供后台新增）
     * @param $tag_data
     * @param $data
     * @param $params
     * @return bool
     */
    private function insertData($tag_data, $params, $data)
    {
        NewProductWikiModel::insert($data);
        $nid = NewProductWikiModel::id();
        $tag_insert_data = [];
        foreach ($tag_data as $k => $tag) {
            if ($tag['_remove_'] !== 1) {
                $tag_insert_data[$k]['tag'] = $tag['tag'];
                $tag_insert_data[$k]['nid'] = $nid;
                $tag_insert_data[$k]['type'] = $params["type"];
            }
        }
        if ($tag_insert_data) {
            NewProductTagModel::insert($tag_insert_data);
        }
        $params['activity_id'] = $nid;
        $this->saveActBasic($params);
        return $nid;
    }

    /**
     * 表单参数校验
     * @param $type
     * @return string[]
     */
    private function _getRules($type)
    {
        $rules = [
            'id' => 'integer',
            "type" => 'required|integer',
            "brand_id" => 'required|integer',
            "brand_name" => 'required',
            "img" => 'required',
            "basic_id" => 'integer',
            "name" => 'required',
            "desc" => 'required',
            "tag" => 'required|array',
            "features" => 'required',
            "start_time" => 'required|date',
            "end_time" => 'required|date',
            "prize_num" => 'integer',
//            "is_delete" => 'required|integer',
//            "status" => 'required|integer',
            "url" => 'url',
        ];

        if ((int)$type === NewProductWikiModel::SUPER_PDT) {
            $rules["question"] = 'required';
        }

        return $rules;
    }

    /**
     * 新增(已关闭)
     * @param Request $request
     * @param Content $content
     * @param Form $form
     * @return Content
     * @deprecated
     */
    public function create(Request $request, Content $content, Form $form): Content
    {
        $form->disableReset();
        $form->text('brand_id', '品牌ID')->required();
        $this->_getForm($form);
        $form->confirm('确定新增吗？');
        $form->action('/admin/newProduct/save');

        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动列表', 'url' => '/newProduct/index'],
                ['text' => '新增']
            )
            ->row($form);
    }

    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function audit(Request $request): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'id' => 'required|int',
                'state' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            $admin_id = Admin::user()->id;
            $data['id'] = $params['id'];
            $data['admin_id'] = $admin_id;
            $data['status'] = $params['state'];
            $info = NewProductWikiModel::first(['id' => $params['id']]);
            if (empty($info)) {
                throw new \Exception('不存在的活动');
            }
            NewProductService::audit($data);
            if ($data['status'] == NewProductWikiModel::STATUS_PASS) {
                BrandActivityBasic::auditNewProAct($data['id']);

                //用户参与营销活动.新品速递
                \Biz\service\brand\BrandGrowth::levelTaskJoin(0, $info['brand_id']);
            }
            if ($data['status'] == NewProductWikiModel::STATUS_REJECT) {//审核不通过，返回活动次数
                BrandActivityBasic::updateActivityState($params['id'], BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT, $info['basic_id'], BrandActivityBasic::ACTIVITY_STATE_DEL);
                BrandEquityVerificationService::activityRightsRefund($info['brand_id'], $params['id'], BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT, $admin_id);
            }
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }

    /**
     * 拖动排序
     * @param Request $request
     */
    public function sort(Request $request): void
    {
        $params = $request->all();
        $sorts = $params['sort'];
        $desc_sorts = array_reverse($sorts);
        $arr = array_flip($sorts);
        $sort_arr = [];
        //将排序更改为倒叙
        foreach ($desc_sorts as $k => $v) {
            $sort_arr[$arr[$k]] = $v;
        }
        if ($sort_arr && is_array($sort_arr)) {
            foreach ($sort_arr as $id => $sort) {
                $data['sort'] = $sort;
                $data['update_time'] = date('Y-m-d H:i:s');
                $data['admin_id'] = Admin::user()->id;
                NewProductWikiModel::update($data, ['id' => $id]);
            }
        }
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \App\Admin\Extensions\WorkContent $content
     * @param $id
     * @return \App\Admin\Extensions\WorkContent
     */
    public function jdCardAdd(Request $request, WorkContent $content, $id): WorkContent
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $infos = NewProductJdCardModel::select('*', ['nid' => $id]);
        $count = count($infos);
        $data = [];
        if ($infos) {
            foreach ($infos as $info) {
                $data["card"][] = $info['jd_num'];
            }
            $data["card"] = implode(',', $data["card"]);
            $data["id"] = $id;
        }
        $form = new Form(['id' => $id, 'card' => $data["card"] ?? '']);
        $form->hidden('id');
        $form->text('card', '已填入的兑换码')->disable();
        if ($count == 0) {
            $form->text('card_1', '兑换码1');
        }
        if ($count <= 1) {
            $form->text('card_2', '兑换码2');
        }
        if ($count <= 2) {
            $form->text('card_3', '兑换码3');
        }
        $form->action('/admin/newProduct/jdCard/save');

        return $content
            ->body($form);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function jdCardSave(Request $request)
    {
        $id = $request->input('id', 0);//活动id
        $cards = array_filter([
            $request->input('card_1', ''),
            $request->input('card_2', ''),
            $request->input('card_3', ''),
        ]);
        //验证京东卡是否已被使用
        $data = NewProductJdCardModel::select('jd_num', ['jd_num' => $cards]) ?? [];
        $count = NewProductJdCardModel::count(['nid' => $id]);
        if ($count >= NewProductJdCardModel::CARD_NUM) {
            $error = new MessageBag(['title' => "该商品已有3张兑换卡了，请勿添加"]);

            return redirect("/admin/newProduct/jdCard/{$id}/add?code=1")->with(compact('error'));
        }
        $cardUsed = implode(',', $data);
        if ($cardUsed) {
            $error = new MessageBag(['title' => "{$cardUsed}已存在，请更换！！！"]);

            return redirect("/admin/newProduct/jdCard/{$id}/add?code=1")->with(compact('error'));
        }
        //保存京东卡号
        if ($cards && $id) {
            foreach ($cards as $card) {
                NewProductJdCardModel::insert([
                    'jd_num' => $card,
                    'nid' => $id,
                    'create_time' => date('Y-m-d H:i:s', time()),
                ]);

            }
            $success = new MessageBag(['title' => '操作成功']);

            return redirect("/admin/newProduct/jdCard/{$id}/add?code=1")->with(compact('success'));

        } else {
            $error = new MessageBag(['title' => '参数错误']);

            return redirect("/admin/newProduct/jdCard/{$id}/add?code=1")->with(compact('error'));
        }

    }

    /**
     * 生成动态图片 prize_img prize_name price brand_name brand_avatar
     * @param $params
     * @return mixed|string
     * @throws \Exception
     */
    private function createImg($params)
    {
        $qrCodeImage = '';
        $tid = mImageCreate::getByWhere(['title' => '新品速递抽奖动态', 'i_status' => mImageCreate::STATUS_PUBLISH], 'id');
        if (!$tid) {
            throw new \Exception('不存在的模版');
        }
        //背景图
        $back_img = 'https://img.haohaozhu.cn/Op-imageShow/8e19030ku0be0rJ00qv74zp?iv=1';
        //奖品图
        $prize_img = $params['prize_img'];
        //光环
        $ring_img = 'https://img.haohaozhu.cn/Op-imageShow/7746a309f04h0Wp00qv6qis?iv=1';
        //奖品名称
        $prize_name = $params['prize_name'] ?: $params['name'];
        //奖品价值
        $prize_price = (string)$params['price'] ?: "价值：0.00";
        //品牌名称背景
        $brand_name_img = 'https://img.haohaozhu.cn/Op-imageShow/d82d830590180uR00qv75n5?iv=1';
        //品牌名称
        $brand_name = $params['brand_name'] ?? '';
        //品牌头像
        $brand_avatar = $params['brand_avatar'] ?? '';
        $data = [
            $back_img,
            $prize_img,
            $ring_img,
            $prize_name,
            $prize_price,
            $brand_name_img,
            $brand_name,
            $brand_avatar
        ];


        $result = ImageCreate::buildImageByTidAndParams($tid, $data, ImageCreate::APP_PIC_MODULE);
        if ($result['code'] && $result['pic_id']) {
            $qrCodeImage = $result['pic_id'];
        }
        $log['params'] = $data;
        $log['res'] = $result;
        Log::debug('生成图片', $log);
        return $qrCodeImage;
    }

    /**
     * 生成中奖图片
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function createImage(Request $request)
    {
        $id = $request->post('id');
        $info = NewProductWikiModel::first(['id' => $id]);
        $brand_logo = \Biz\service\brand\Brand::getBrandInfoByIds4Goods([$info['brand_id']])[$info['brand_id']]['logo'] ?? '';
        $dynamicImg = '';
        $price = $info['price'] ? bcdiv($info['price'], 100, 2) : "0.00";
        $data = [
            'prize_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $info['img'], ImgUrl::IMAGE_SIZE_ORI_NPHONE) ?? '',
            'prize_name' => self::sub_str($info['prize_name'], 12),
            'price' => "价值：" . $price . '元',
            'brand_name' => self::sub_str($info['brand_name'], 6),
            'brand_avatar' => $brand_logo,
            'name' => $info['name'],
        ];

        try {
            $dynamicImg = $this->createImg($data);
            NewProductWikiModel::update([
                'dynamic_img' => $dynamicImg,
                'dynamic_status' => NewProductWikiModel::CREATED
            ], ['id' => $id]);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public static function activityData(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        $info = NewProductWikiModel::get(['id', 'brand_name', 'name', 'activity_data'], ['id' => $id]);
        $form = new Form($info);
        $form->text('id', '活动id')->readonly();
        $form->text('brand_name', '品牌名称')->readonly();
        $form->text('name', '商品名称')->readonly();
        $form->textarea('activity_data', '活动数据')->required()->rows(10);
        $form->action('/admin/newProduct/index/activityDataPost');
        return $content->header('活动数据')
            ->row($form);
    }

    public static function activityDataPost(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $activityData = $params['activity_data'] ?? '';
        try {
            if (empty($id)) {
                throw new \Exception('id为空');
            }
            $res = NewProductWikiModel::update(['activity_data' => $activityData], ['id' => $id]);
            if ($res->rowCount()) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
            return redirect("/admin/newProduct/index/'.$id.'/activityData?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    /**
     * @param $str
     * @param int $len
     * @return string
     */
    public static function sub_str($str, int $len = 1): string
    {
        $strlen = strlen($str) / 3;
        if ($strlen < $len) {
            return $str;
        } else {
            return mb_substr($str, 0, $len, "utf-8") . "...";
        }
    }


    private function createImgScript()
    {
        return <<<SCRIPT
        $('.edit-create').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/newProduct/createImage/'
            let params = {id:id}
            swal({
                    title: "确认生成吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                    //ajax
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
                    //ajax-end
                    }
            });
        });
       
SCRIPT;
    }
}